package com.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pojo.*;
import com.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/blog")
public class BlogController {

    private BlogService blogService;
    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    @Qualifier("blogServiceImpl")
    public void setBlogService(BlogService blogService) {
        this.blogService = blogService;
    }

    /**
     * 发布博客
     *
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/releaseBlog")
    public String releaseBlog(@RequestParam Map<String, Object> map) throws JsonProcessingException {

        //插入博客
        String bid = blogService.releaseBlog(map);
        map.put("bid", bid);
        blogService.insertLabel(map);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "发布成功");

        String str = objectMapper.writeValueAsString(res);
        return str;
    }

    /**
     * 处理富文本编辑器插入的照片
     *
     * @param multipartFiles
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    public UploadImg uploadImg(
            @RequestParam("imgFile") MultipartFile[] multipartFiles,
            HttpServletRequest request) throws IOException {

        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
        String accessKeyId = "";
        String accessKeySecret = "";
        String bucketName = "";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        List<String> url = new ArrayList<>();
        for (MultipartFile multipartFile : multipartFiles) {
            String fileName = UUID.randomUUID().toString().replaceAll("-", "");
            //获取文件名
            String name = multipartFile.getOriginalFilename();
            //将文件名按.分割
            String[] files = name.split("\\.");

            // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
            String objectName = "upload/"+fileName+"."+files[files.length-1];
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(multipartFile.getBytes()));

            url.add("" + objectName);

        }
        // 关闭OSSClient。
        ossClient.shutdown();
        UploadImg uploadImg = new UploadImg(0, url);
        return uploadImg;
    }

    /**
     * 查询所有的分类
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryAllBlogType")
    public String queryAllBlogType(int start) throws JsonProcessingException {
        List<BlogType> blogTypes = blogService.queryAllBlogType(start);
        String types = objectMapper.writeValueAsString(blogTypes);
        return types;
    }

    /**
     * 查询所有的标签
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryAllBlogLabel")
    public String queryAllBlogLabel(int start) throws JsonProcessingException {
        List<BlogLabel> blogLabels = blogService.queryAllBlogLabel(start);
        String labels = objectMapper.writeValueAsString(blogLabels);
        return labels;
    }

    @RequestMapping("/queryHotBlogLabel")
    public String queryHotBlogLabel() throws JsonProcessingException {
        List<BlogLabel> blogLabels = blogService.queryHotBlogLabel();
        String labels = objectMapper.writeValueAsString(blogLabels);
        return labels;
    }

    /**
     * 查询博客相关信息
     *
     * @param start
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryAllBlogMessage")
    public String queryAllBlogMessage(@RequestParam int start) throws JsonProcessingException {
        List<Blog> blogList = blogService.queryAllBlogMessage(start);
        blogService.countAllType();
        blogService.countAllLabel();
        String str = objectMapper.writeValueAsString(blogList);
        return str;
    }

    /**
     * 统计博客数量
     *
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/countBlogNumber")
    public String countBlogNumber() throws JsonProcessingException {
        int i = blogService.countBlogNumber();
        String s = objectMapper.writeValueAsString(i);
        return s;
    }

    /**
     * 根据分类统计博客数量
     * @param tid
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/countBlogNumberByTid")
    public String countBlogNumberByTid(String tid) throws JsonProcessingException {
        System.out.println("========"+tid);
        int i = blogService.countBlogNumberByTid(tid);
        String s = objectMapper.writeValueAsString(i);
        return s;
    }

    /**
     * 修改博客信息
     *
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/updateBlog")
    public String updateBlog(@RequestParam Map<String, Object> map) throws JsonProcessingException {
        blogService.updateBlog(map);
        blogService.updateBlogLabel(map);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "博客已更新");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 删除博客
     *
     * @param bid
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/deleteBlog")
    public String deleteBlog(@RequestParam Map<String, String> bid) throws JsonProcessingException {

        blogService.deleteBlog(bid);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.DELETE_SUCCESS);
        res.put("tip", "博客删除成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 插入新标签
     *
     * @param label
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/insertLabel")
    public void insertLabel(@RequestParam String label) throws JsonProcessingException {
        blogService.insertLabel(label);
    }

    /**
     * 检查标签是否存在
     * @param label
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/checkLabelExist")
    public String checkLabelExist(@RequestParam String label) throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        String s = blogService.queryLidByName(label);
        if (s != null) {
            map.put("status", Status.LABEL_EXIST);
            map.put("tip", "标签已存在");
        } else {
            map.put("status", Status.LABEL_NOEXIST);
            map.put("tip", "标签不存在");
        }
        String res = objectMapper.writeValueAsString(map);
        return res;
    }

    /**
     * 修改标签
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/updateLabel")
    public String updateLabel(@RequestParam Map<String, String> map) throws JsonProcessingException {
        BlogLabel blogLabel = new BlogLabel();
        blogLabel.setLabelName(map.get("labelName"));
        blogLabel.setLid(map.get("lid"));
        blogService.updateLabel(blogLabel);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "标签修改成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 删除标签
     * @param lid
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/deleteLabel")
    public String deleteLabel(@RequestParam String lid) throws JsonProcessingException {
        blogService.deleteLabel(lid);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "标签删除成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 添加分类
     * @param type
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/insertType")
    public String insertType(String type) throws JsonProcessingException {
        blogService.insertType(type);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "分类添加成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 修改分类
     * @param map
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/updateType")
    public String updateType(@RequestParam Map<String, String> map) throws JsonProcessingException {
        blogService.updateType(map);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "分类修改成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 检查分类是否存在
     * @param type
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/checkTypeExist")
    public String checkTypeExist(String type) throws JsonProcessingException {
        BlogType blogType = blogService.queryTypeByName(type);
        Map<String, Object> map = new HashMap<>();
        if (blogType != null) {
            map.put("status",Status.TYPE_EXIST);
            map.put("tip","分类已存在");
        }else {
            map.put("status",Status.TYPE_NOEXIST);
            map.put("tip","分类不存在");
        }

        String s = objectMapper.writeValueAsString(map);
        return s;
    }

    /**
     * 删除分类
     * @param type
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/deleteType")
    public String deleteType(String type) throws JsonProcessingException {
        blogService.deleteType(type);

        Map<String, Object> res = new HashMap<>();
        res.put("status", Status.RELEASE_SUCCESS);
        res.put("tip", "分类删除成功");
        String s = objectMapper.writeValueAsString(res);
        return s;
    }

    /**
     * 根据分类id查询博客信息
     * @param tid
     * @param start
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryBlogByTid")
    public String queryBlogMessageByTid(String tid,int start) throws JsonProcessingException {
        List<Blog> blogList = blogService.queryBlogMessageByTid(tid,start);
        String s = objectMapper.writeValueAsString(blogList);
        return s;
    }

    /**
     * 根据标签id查询博客信息
     * @param lid
     * @param start
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryBlogByLid")
    public String queryBlogMessageByLid(String lid,int start) throws JsonProcessingException {
        List<Blog> blogList = blogService.queryBlogMessageByLid(lid, start);
        String s = objectMapper.writeValueAsString(blogList);
        return s;
    }

    /**
     * 插入评论
     * @param comment
     */
    @RequestMapping("/insertComment")
    public void insertComment(@RequestBody Comment comment){
        System.out.println(comment);
        blogService.insertComment(comment);
    }

    /**
     * 根据博客id查询所有评论
     * @param bid
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryComment")
    public String queryCommentByBid(String bid) throws JsonProcessingException {
        List<Node> comments = blogService.queryCommentByBid(bid);
        String s = objectMapper.writeValueAsString(comments);
        return s;
    }

    /**
     * 统计当前博客的评论数量
     * @param bid
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/countCommentsNum")
    public String countCommentsNum(String bid) throws JsonProcessingException {
        int i = blogService.countCommentsNum(bid);
        String s = objectMapper.writeValueAsString(i);
        return s;
    }

    /**
     * 根据关键词搜索
     * @param param
     * @param start
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/searchBlog")
    public String searchBlog(@RequestParam("param") String param,@RequestParam("start") int start, @RequestParam("type") String type) throws JsonProcessingException {
        Map<String, Object> map=new HashMap<>();
        List<Blog> list = new ArrayList<>();
        String s=null;
        if (type.equals("keyword")) {
            map = blogService.searchBlogByKeyword(param, start);
            s=objectMapper.writeValueAsString(map);
        }else if (type.equals("type")){
            list = blogService.queryBlogMessageByTid(param, start);
            s=objectMapper.writeValueAsString(list);
        }else if (type.equals("label")){
            String lid = blogService.queryLidByName(param);
            list = blogService.queryBlogMessageByLid(lid,start);
            s=objectMapper.writeValueAsString(list);
        }
        return s;
    }

    /**
     * 查询阅读量前十
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping("/queryTopTen")
    public String queryBlogTopTen() throws JsonProcessingException {
        List<Blog> blogList = blogService.queryBlogTopTen();
        String s = objectMapper.writeValueAsString(blogList);
        return s;
    }

    /**
     * 更新博客阅读量
     * @param bid
     * @param reads
     */
    @RequestMapping("/updateBlogReads")
    public void updateBlogReads(@RequestParam("bid") String bid,@RequestParam("reads") int reads){

        blogService.updateBlogReads(bid, reads);
    }

    @RequestMapping("/queryClickRate")
    public String queryClickRateByName(String label) throws JsonProcessingException {
        int i = blogService.queryClickRateByName(label);
        String s = objectMapper.writeValueAsString(i);
        return s;
    }

    @RequestMapping("/interceptor")
    public boolean adminInterceptor(String username, HttpServletRequest request){
        HttpSession session = request.getSession();
        return session.getAttribute(username)!=null;
    }
}
